<?php

namespace Inter\ArticleClientBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Inter\ArticleBundle\Entity\Comment;
use Symfony\Component\HttpFoundation\Request;

class ArticleController extends Controller
{
    public function indexAction(Request $request)
    {
    	
    	$em = $this->getDoctrine()
    	->getEntityManager();
    	
    	$articles = $em->createQueryBuilder()
    	->select('b')
    	->from('InterArticleBundle:Article',  'b')
    	->addOrderBy('b.createdat', 'DESC')
    	->getQuery()
    	->getResult();
    	
    	$cache_key = 'article_cache_admin_listarticle';
    	$cache = $this->get('liip_doctrine_cache.ns.interarticle');
    	
    	if (false === ($cached_data = $cache->fetch($cache_key))) {
    		$cached_data = $articles;
    		$cache->save($cache_key, $cached_data, 3600);//TTL 1h
    	}
    	 
    	 
    	$paginator  = $this->get('knp_paginator');
    	$pagination = $paginator->paginate(
    			$cached_data,
    			$request->query->get('page', 1)/*page number*/,
    			5/*limit per page*/
    	);
    	
    	//foreach ($articles as $article) {
    		//$comments = ($article->getComments());
    		//echo count($comments);
    	//}
    	
    	//exit;
    	 return $this->render('ArticleClientBundle:Article:home.html.twig', array(
    			'pagination' => $pagination,
    	));
    	
        
        
    }
    
    public function showAction($id, $slug)
    {
    	$em = $this->getDoctrine()->getEntityManager();
    	
    	$article = $em->getRepository('InterArticleBundle:Article')->find($id);
    	
    	if (!$article) {
    		throw $this->createNotFoundException('Unable to find Article post.');
    	}
    	
    	$comments = $em->getRepository('InterArticleBundle:Comment')
    				->getCommentsForBlog($article->getId());
    	 
    	
    	
    	return $this->render('ArticleClientBundle:Article:show.html.twig', array(
    			'article'      => $article,
    			'comments'		=> $comments,
    	));
    }
    
    
    
    
    
}
